package setting

import (
	"cs/internal/utils"
	"log"
	"os"
	"path/filepath"
	"time"

	"gopkg.in/yaml.v2"
)

var (
	Config *Conf
)

type Conf struct {
	Database Database `yaml:"database"`
	Redis    Redis    `yaml:"redis"`
	App      App      `yaml:"app"`
}

// setting.App.Ch
type App struct {
	RunMode     string `yaml:"run-mode"`
	PageSize    int    `yaml:"page-size"`
	IdentityKey string `yaml:"identity-key"`
	LogPath     string `yaml:"log-path"`
	AesKey      string `yaml:"aes-key"`
	GoNum       int    `yaml:"go-num"`
	DataPath    string `yaml:"dataPath"`
	OldDataPath string `yaml:"oldDataPath"`
	QuchongPath string `yaml:"quchongPath"`
	DelPath     string `yaml:"delPath"`
	Ch          chan int
}

type Database struct {
	Type            string `yaml:"type"`
	User            string `yaml:"user"`
	Password        string `yaml:"password"`
	Host            string `yaml:"host"`
	Name            string `yaml:"name"`
	TablePrefix     string `yaml:"table-prefix"`
	SetMaxIdleConns int    `yaml:"setMaxIdleConns"`
	SetMaxOpenConns int    `yaml:"setMaxOpenConns"`
}

type Redis struct {
	Addr        string        `yaml:"addr"`
	Pass        string        `yaml:"pass"`
	DB          int           `yaml:"db"`
	Timeout     time.Duration `yaml:"timeout"`
	ExpiredTime int           `yaml:"expired-time"`
}

func init() {
	Config = getConf()
	log.Println("[Setting] Config init success")
}

func getConf() *Conf {
	var c *Conf

	fileDir := utils.GetFilePath()
	log.Println("Config file path: ", fileDir)

	// 拼接到 config.yaml 的绝对路径
	configPath := filepath.Join(fileDir, "../../../config/config.yaml")
	file, err := os.ReadFile(configPath)
	if err != nil {
		log.Println("[Setting] getConf config error: ", err)
	}
	err = yaml.UnmarshalStrict(file, &c)
	if err != nil {
		log.Println("[Setting] yaml unmarshal error: ", err)
	}
	return c
}
